package com.example.administrator.printoutindemo.mvp.ui.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dds.soap.SoapListener;
import com.dds.soap.SoapParams;
import com.dds.soap.SoapUtil;
import com.example.administrator.printoutindemo.R;
import com.example.administrator.printoutindemo.di.component.DaggerKuCunComponent;
import com.example.administrator.printoutindemo.di.module.KuCunModule;
import com.example.administrator.printoutindemo.mvp.contract.KuCunContract;
import com.example.administrator.printoutindemo.mvp.presenter.KuCunPresenter;
import com.example.administrator.printoutindemo.mvp.ui.adapter.KuCunAdapter;
import com.example.administrator.printoutindemo.mvp.ui.entity.InventoryAndroid;
import com.example.administrator.printoutindemo.mvp.ui.entity.KuCun;
import com.example.administrator.printoutindemo.mvp.ui.view.KuCunRightSideslipLay;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.base.BaseConstants;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.LogUtils;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.xiaoxing.gifloadingview.LoadingDialogUtil;

import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import me.jessyan.armscomponent.commonres.utils.ToolbarUtils;
import me.jessyan.armscomponent.commonres.view.RecycleViewDivider;
import me.jessyan.armscomponent.commonsdk.core.RouterHub;

import static com.jess.arms.utils.Preconditions.checkNotNull;


@Route(path = RouterHub.ACTIVITY_KU_CUN)
public class KuCunActivity extends BaseActivity<KuCunPresenter> implements KuCunContract.View, KuCunRightSideslipLay.FlowingDrawerInterface, OnRefreshListener, OnLoadMoreListener {

    @BindView(R.id.empty)
    View mEmptyLayout;
    @BindView(R.id.empty_text)
    TextView empty_text;
    @BindView(R.id.empty_image)
    ImageView empty_image;

    @BindView(R.id.drawer_layout)
    DrawerLayout mDrawer;
    @BindView(R.id.nav_view)
    LinearLayout navigationView;
    @BindView(R.id.btnRight)
    TextView mBtnRight;
    @BindView(R.id.refreshLayout)
    RefreshLayout mRefreshLayout;
    private RecyclerView recyclerView;
    private KuCunAdapter mAdapter;
    private KuCunRightSideslipLay menuHeaderView;
    private List<InventoryAndroid> mInventoryAndroidList = new ArrayList<>();
    private String mSid = "";
    private String mProid = "";
    private String mProjectname = "";
    private String mPurchaseid = "";
    private String mMaterial = "";
    private String mSupplier;

    @Override
    public void flowingDrawerClose() {
        closeMenu();
    }

    public void closeMenu() {
        mDrawer.closeDrawer(GravityCompat.END);
    }

    @Override
    public void search(String sid, String proid, String projectname, String purchaseid, String material, String supplier) {
        mStart = 1;

        mSid = sid;
        mProid = proid;
        mProjectname = projectname;
        mPurchaseid = purchaseid;
        mMaterial = material;
        mSupplier = supplier;

        closeMenu();
        hideData();
        mInventoryAndroidList.clear();
        getData(mSharedPreferencesHelper.getString(BaseConstants.UID), sid, proid, projectname, purchaseid, material,supplier);

    }

    private void hideData() {
        mEmptyLayout.setVisibility(View.VISIBLE);
        recyclerView.setVisibility(View.GONE);
    }

    /**
     * @param user_id     用户id
     * @param sid         仓库id
     * @param proid       项目编号
     * @param projectname 项目名称
     * @param purchaseid  订单号
     * @param material    物料名称
     */
    private void getData(String user_id, String sid, String proid, String projectname, String purchaseid, String material, String supplier) {

        showLoading();

//        String methodName = "GetInventoryForLeader";//没有添加分页的
        String methodName = "GetInventoryForLeaderPaging"; //添加分页

        String roleId = mSharedPreferencesHelper.getString(BaseConstants.ROLE_NAME);

        if (roleId.equals(BaseConstants.LoginRole.CANG_GUAN_YUAN.getValue())) {
            methodName = "GetInventoryForCgyPaging"; //添加分页
        }
        LogUtils.debugEInfo("sid==" + sid);
        SoapUtil soapUtil = SoapUtil.getInstance(this);
        soapUtil.setDotNet(true);
        SoapParams params = new SoapParams();
        params.put("user_id", user_id);
        params.put("sid", sid);
        params.put("proid", proid);
        params.put("projectname", projectname);
        params.put("purchaseid", purchaseid);
        params.put("material", material);
        params.put("supplier", supplier);
        params.put("startIndex", String.valueOf(mStart));
        params.put("endIndex", String.valueOf(mStart + mNum - 1));
        /**
         * 请求
         */
        String finalMethodName = methodName;
        soapUtil.callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();

                String result = object.getProperty(finalMethodName + "Result").toString();
                if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {
                    List<InventoryAndroid> inventoryAndroidList = new Gson().fromJson(result, new TypeToken<List<InventoryAndroid>>() {
                    }.getType());

                    if (inventoryAndroidList != null && inventoryAndroidList.size() > 0) {
                        mStart += inventoryAndroidList.size();

//                        mInventoryAndroidList.clear();
                        mInventoryAndroidList.addAll(inventoryAndroidList);
                        mAdapter.notifyDataSetChanged();
                        showData();

                    }
                } else {
//                    hideData();
                    showMessage("没有更多数据");

                }

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();

                hideData();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
                hideData();
            }
        }, getAapiUserName(), getApiPwd());


    }

    @Override
    public void showLoading() {
        LoadingDialogUtil.showGifdialog2(getSupportFragmentManager(), R.drawable.public_loading);
    }

    private void showData() {
        mEmptyLayout.setVisibility(View.GONE);
        recyclerView.setVisibility(View.VISIBLE);
    }

    @Override
    public void hideLoading() {
        LoadingDialogUtil.dismissDialog();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.makeText(this, message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {

    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        getData(mSharedPreferencesHelper.getString(BaseConstants.UID), mSid, mProid, mProjectname, mPurchaseid, mMaterial,mSupplier);
        mRefreshLayout.finishLoadMore();
    }

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerKuCunComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .kuCunModule(new KuCunModule(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_ku_cun; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {

        ToolbarUtils.initToolbarTitleBack(this, getString(R.string.activity_ku_cun));
//        getKuCunData();
        initEmpty();
        initRefreshLayout();
        initBtnRight();
        initDrawer();
        initRecyclerView();


        getData(mSharedPreferencesHelper.getString(BaseConstants.UID), "", "", "", "", "","");
    }

    private void initEmpty() {
        empty_image.setImageResource(com.xiaoxing.zhinenghuacangku.R.drawable.ic_empty);
        empty_text.setTextColor(Color.parseColor("#CFCFCF"));
        empty_text.setText("暂无数据");
    }

    private void initRefreshLayout() {
        mRefreshLayout.setRefreshHeader(new
                ClassicsHeader(this).setSpinnerStyle(SpinnerStyle.FixedBehind).setPrimaryColorId(com.xiaoxing.zhinenghuacangku.R.color.public_colorPrimary).setAccentColorId(android.R.color.white));
        mRefreshLayout.setOnRefreshListener(this);
        mRefreshLayout.setOnLoadMoreListener(this);
        mRefreshLayout.setEnableRefresh(false);
        mRefreshLayout.setEnableLoadMore(true);
    }

    private void initBtnRight() {
        mBtnRight.setText("筛选");
        mBtnRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openMenu();
            }
        });
    }

    private void initDrawer() {
        mDrawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, Gravity.RIGHT);

        menuHeaderView = new KuCunRightSideslipLay(KuCunActivity.this, this, mSharedPreferencesHelper.getString(BaseConstants.UID), mSharedPreferencesHelper);
        navigationView.addView(menuHeaderView);

        menuHeaderView.setCloseMenuCallBack(new KuCunRightSideslipLay.CloseMenuCallBack() {
            @Override
            public void setupCloseMean() {
                closeMenu();
            }
        });
    }

    private void initRecyclerView() {
        recyclerView = findViewById(R.id.recyclerView);
        recyclerView.addItemDecoration(new RecycleViewDivider(this, LinearLayoutManager.HORIZONTAL, 20, getResources().getColor(R.color.public_client_line_color)));
        mAdapter = new KuCunAdapter(this, mInventoryAndroidList);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

//                ArmsUtils.makeText(getContext(), "position=0" + position);
            }
        });

    }


    public void openMenu() {
        mDrawer.openDrawer(GravityCompat.END);
    }

    private List<InventoryAndroid> loadModels() {
        List<InventoryAndroid> addressLists = new ArrayList<>();


        InventoryAndroid addressList = new InventoryAndroid();
        addressLists.add(addressList);

        InventoryAndroid addressList1 = new InventoryAndroid();
        addressLists.add(addressList1);

        InventoryAndroid addressList2 = new InventoryAndroid();
        addressLists.add(addressList2);

        InventoryAndroid addressList3 = new InventoryAndroid();
        addressLists.add(addressList3);


        return addressLists;
    }

    private void getKuCunData() {
        mPresenter.getKuCunData();
    }

    @Override
    public void getKuCunDataSuccess(KuCun entityData) {


    }


}
